package com.mjp.learn.multi.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock
 * 重入锁
 * reentrantLock相当于独享锁
 */
public class Demo01 implements Runnable {
    //可重入锁
    public static ReentrantLock lock = new ReentrantLock();

    //volatile可以保证变量在线程之中的可见性,防止指令重排序
    public static volatile int count = 0;

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            lock.lock();
            try {
                count++;
            } finally {
                lock.unlock();
            }
        }
        System.out.println(Thread.currentThread().getName() + ": end!");
    }

    public static void main(String[] args) {
        Demo01 demo = new Demo01();
        Thread t1 = new Thread(demo);
        Thread t2 = new Thread(demo);
        t1.start();t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
}
